package com.hs.kfk.serializer;

import org.apache.kafka.common.serialization.Serializer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @Description: User序列化类
 * @Author 胡尚
 * @Date: 2024/8/8 12:41
 */
public class UserSerializer implements Serializer<User> {
    @Override
    public byte[] serialize(String topic, User data) {
        // 简单粗暴的方式  直接转json
        // byte[] bytes = JSON.toJSON(data).toString().getBytes(StandardCharsets.UTF_8);

        // 传输效率更高的方式
        byte[] userNameBytes = data.getUsername().getBytes(StandardCharsets.UTF_8);
        // id:Long8字节 + 4字节保存不定长长度 + username不定长长度 + age int 4字节
        int cap = 8 + 4 + userNameBytes.length + 4;
        ByteBuffer byteBuffer = ByteBuffer.allocate(cap);
        byteBuffer.putLong(data.getuId());
        byteBuffer.putInt(userNameBytes.length);
        byteBuffer.put(userNameBytes);
        byteBuffer.putInt(data.getAge());
        return byteBuffer.array();
    }
}
